package com.wfh.frp.handler;

import com.wfh.frp.model.ProxyMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Title: ServiceToTargetHandler
 * @Author wangfenghuan
 * @Package com.wfh.frp.handler
 * @Date 2025/10/8 14:01
 * @description: 内网服务处理器
 */
public class ServiceToTargetHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final Channel proxyChannel;

    private final String channelId;

    public ServiceToTargetHandler(Channel proxyChannel, String channelId){
        this.channelId = channelId;
        this.proxyChannel = proxyChannel;
    }

    /**
     * 收到消息
     * @param channelHandlerContext
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        // 读取到了内网服务的响应，转发给server进而给visitor
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);

        ProxyMsg proxyMsg = new ProxyMsg();
        proxyMsg.setType(ProxyMsg.TRANSFER);
        proxyMsg.setChannelId(channelId);
        proxyMsg.setData(bytes);

        proxyChannel.writeAndFlush(proxyMsg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
